package com.onlyyou.user.service.Impl;

import com.alibaba.fastjson.JSON;
import com.onlyyou.user.dao.IUserDao;
import com.onlyyou.user.entity.User;
import com.onlyyou.user.enums.ResultEnum;
import com.onlyyou.user.enums.UserPermissionEnum;
import com.onlyyou.user.exception.UserException;
import com.onlyyou.user.info.UserInfo;
import com.onlyyou.user.mapper.UserMapper;
import com.onlyyou.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.*;

/**
 * @Author: 小野
 * @Date: 2020/1/12 15:43
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Autowired
    private IUserDao iUserDao;

    @Override
    public Integer queryRows() {
        return userMapper.rows();
    }

    @Override
    public UserInfo findStatus(Long userId) {
        UserInfo userInfo = findById(userId);
        String key = "user_" + userInfo.getUsername();
        Boolean status = stringRedisTemplate.hasKey(key);
        if (!status)
            throw new UserException(ResultEnum.NO_LOGIN);
        String userRedis = stringRedisTemplate.opsForValue().get(key);
        UserInfo userInfoStatus = JSON.parseObject(userRedis, UserInfo.class);
        return userInfo;
    }

    @Override
    public UserInfo findById(Long userId) {
        User user = userMapper.findById(userId);
        if (null == user)
            throw new UserException(ResultEnum.NULL);
        return user.buildInfo();
    }

    public Map<String, Object> getUser(String username, String password) {
        Map<String, Object> resultMap = new HashMap<String, Object>();

        //1、判断传入的参数
        if (username == null || username.equals("")) {
            resultMap.put("result", false);
            resultMap.put("msg", "用户名不能为空！");
            return resultMap;
        }

        //2、调userdao的方法
        ArrayList<Map<String, Object>> list = iUserDao.getUser(username, password);

        //3、如果没有查询到返回错误信息
        if (list == null || list.size() == 0) {
            resultMap.put("result", false);
            resultMap.put("msg", "没有查询到数据！");
            return resultMap;
        }

        //4、返回正常信息
        resultMap = list.get(0);
        resultMap.put("result", true);
        resultMap.put("msg", "");
        return resultMap;
    }

    public Map<String, Object> insertUser(String username, String password) {
        Map<String, Object> resultMap = new HashMap<String, Object>();

        //1、判断传入的参数
        if (username == null || username.equals("")) {
            resultMap.put("result", false);
            resultMap.put("msg", "用户名不能为空！");
            return resultMap;
        }

        int new_id = iUserDao.insertUser(username, password);

        resultMap.put("user_id", new_id);
        resultMap.put("username", username);
        resultMap.put("phone", username);
        resultMap.put("password", password);
        resultMap.put("result", true);
        resultMap.put("msg", "");
        return resultMap;
    }

    /**
     * 注销
     *
     * @param username
     */
    @Override
    public void logout(String username) {
        /**
         * 注销业务  删除redis中的数据
         */
        String key = "user_" + username;
        Boolean hasKey = stringRedisTemplate.hasKey(key);
        if (!hasKey) {
            //不存在
            throw new UserException(ResultEnum.LOGOUT_ERROR);
        }
        stringRedisTemplate.delete(key);
    }

    /**
     * 商家及管理员登录
     */
    @Override
    public UserInfo adminLogin(String username, String password) {
        UserInfo userInfo = login(username, password);
        if (userInfo.getPermission() <= UserPermissionEnum.USER.getStatus()) {
            throw new UserException(ResultEnum.NO_PERMISSION);
        }
        return userInfo;
    }

    /**
     * 普通登录
     */
    @Override
    public UserInfo login(String username, String password) {
        UserInfo userInfo = findByName(username);
        if (!userInfo.getPassword().equals(password)) {
            throw new UserException(ResultEnum.PASSWORD_ERROR);
        }
        return userInfo;

    }

    /**
     * 查询所有用户
     */
    @Override
    public List<User> findAll(Long userId, Integer pages, Integer rows) {
        UserInfo userInfo = findById(userId);
        if (userInfo.getPermission() <= UserPermissionEnum.USER.getStatus()) {
            throw new UserException(ResultEnum.NO_PERMISSION);
        }
        return userMapper.findAll(pages, rows);
    }

    @Override
    public UserInfo findByName(String username) {
        //获取redis中的数据
        String key = "user_" + username;
        Boolean hasKey = stringRedisTemplate.hasKey(key);
        if (hasKey) {
            //redis 中有数据
            String strUser = stringRedisTemplate.opsForValue().get(key);
            UserInfo userInfo = JSON.parseObject(strUser, UserInfo.class);
            return userInfo;
        }
        User user = userMapper.findByName(username);
        if (null == user) {
            throw new UserException(ResultEnum.NULL);
        }
        //存入redis中
        String json = JSON.toJSONString(user.buildInfo());
        stringRedisTemplate.opsForValue().set(key, json);
        return user.buildInfo();
    }

    @Override
    public UserInfo add(UserInfo user) {
        if (null != userMapper.findByName(user.getUsername())) {
            throw new UserException(ResultEnum.EXISTING);
        }
        userMapper.add(user.buildInfo());
        User userFind = userMapper.findById(user.getId());
        if (null== userFind){
            throw new UserException(ResultEnum.SAVE_NULL);
        }
        return userFind.buildInfo();
    }

    @Override
    @Transactional
    public User update(User user) {
        if (null == userMapper.findById(user.getId())) {
            throw new UserException(ResultEnum.NULL);
        }
        String key = "uesr_" + user.getUsername();
        Boolean hasKey = stringRedisTemplate.hasKey(key);
        if (hasKey) {
            stringRedisTemplate.delete(key);
        }
        User updateUser = userMapper.update(user);
        stringRedisTemplate.opsForValue().set(key, JSON.toJSONString(updateUser.buildInfo()));
        return updateUser;
    }
}
